# -*- coding: utf-8 -*-

import wx
import wx.lib.masked as masked

__all__ = ['create']

def create(parent, date="", time="", enable=True):
    """
    return class WbDateTime(wx.Panel).
    date - "2009-7-1"
    time - "14:59:59"
    enable - True or False
    """
    return WbDateTime(parent, date, time, enable)

class WbDateTime(wx.Panel):
    def __init__(self, parent, date="", time="", enable=True):
        """
        WbDateTime Panel.
        date - "2009-7-1"
        time - "14:59:59"
        enable - True or False
        """
        wx.Panel.__init__(self, parent, size=(-1, 23))
        
        self.date = date
        self.time = time
        self.enable = enable
        
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.SetSizer(sizer)
        
        self.dateCtl = wx.DatePickerCtrl(self)
        self.Bind(wx.EVT_DATE_CHANGED, self.OnDateChanged, self.dateCtl)
        sizer.Add(self.dateCtl, 0, wx.EXPAND, 0)
        
        h = self.dateCtl.GetSize().height
        spin = wx.SpinButton(self, size=(-1, h), style=wx.SP_VERTICAL)
        self.timeCtl = masked.TimeCtrl(self, fmt24hr=True, 
                spinButton=spin)
        self.Bind(masked.EVT_TIMEUPDATE, self.OnTimeChanged, self.timeCtl)
        sizer.Add(self.timeCtl, 0, wx.EXPAND, 0)
        sizer.Add(spin, flag=wx.ALIGN_BOTTOM)
        
        self.update(self.date, self.time, self.enable)
    
    def OnDateChanged(self, evt):
        #print "OnDateChanged: %s\n" % evt.GetDate()
        self.date = evt.GetDate().FormatISODate()
    
    def OnTimeChanged(self, evt):
        #print "OnTimeChanged: %s\n" % evt.GetValue()
        self.time = evt.GetValue()
    
    def update(self, date="", time="", enable=True):
        if date:
            dt = wx.DateTime()
            dt.ParseDate(date)
            self.dateCtl.SetValue(dt)
        if time:
            self.timeCtl.SetValue(time)
        self.Enable(enable)
    
    def getDateTime(self):
        dt = wx.DateTime()
        dt.ParseDateTime("%s %s" % (self.date, self.time))
        return dt
    
    def getPyTime(self):
        from pywintypes import Time
        ymd = map(int, self.date.split('-'))
        hms = map(int, self.time.split(':'))
        return Time( ymd + hms )

class TestFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1)
        
        p1 = WbDateTime(self, date="1986-10-27")
        p2 = WbDateTime(self, time="14:45:00", enable=False)
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(p1, 0, wx.ALL, 5)
        sizer.Add(p2, 0, wx.ALL, 5)
        
        self.SetSizer(sizer)
        self.Fit()

if __name__ == '__main__':
    app = wx.PySimpleApp()
    TestFrame().Show()
    app.MainLoop()
    